package org.nicocube.airain.domain.server.criteria;

import java.util.Collection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.db4o.query.Constraint;
import com.db4o.query.Query;

/**
 * Build a complex query constraint for finding all the object that has the value of a column present in a collection  
 * 
 * @author nicolas
 * @version 0.1
 * 
 * @param <T>
 */
public class InCriteria<T> extends ConstraintCriteria<Collection<T>> implements Criteria {
	private static final Logger log = LoggerFactory.getLogger(InCriteria.class); 
	
	/**
	 * Build the Criteria
	 * 
	 * @param column the column to set the Constraint on
	 * @param value the Collection of value to check this column 
	 */
	public InCriteria(String column, Collection<T> value) {
		super(column, value);
	}

	@Override
	public void apply(Query q) {
		if (log.isDebugEnabled()) log.debug("apply "+getValue());
		
		Object[] l = getValue().toArray();

		Constraint c = q.descend(getColumn()).constrain(l[0]);
		
		for (int i = 1 ; i < l.length-1 ; i++ ) 
			c = c.or(q.descend(getColumn()).constrain(l[i]));

		q.descend(getColumn()).constrain(l[l.length-1]).or(c);
		
	}
}
